package com.baobao.service;

import com.baobao.dao.NoticeDAO;

import com.baobao.domain.Notice;

import java.util.Calendar;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

/**
 * Spring service that handles CRUD requests for Notice entities
 * 
 */

@Service("NoticeService")
@Transactional
public class NoticeServiceImpl implements NoticeService {

	/**
	 * DAO injected by Spring that manages Notice entities
	 * 
	 */
	@Autowired
	private NoticeDAO noticeDAO;

	/**
	 * Instantiates a new NoticeServiceImpl.
	 *
	 */
	public NoticeServiceImpl() {
	}

	/**
	 */
	@Transactional
	public Notice findNoticeByPrimaryKey(String schoolId, Calendar time) {
		return noticeDAO.findNoticeByPrimaryKey(schoolId, time);
	}

	/**
	 * Load an existing Notice entity
	 * 
	 */
	@Transactional
	public Set<Notice> loadNotices() {
		return noticeDAO.findAllNotices();
	}

	/**
	 * Delete an existing Notice entity
	 * 
	 */
	@Transactional
	public void deleteNotice(Notice notice) {
		noticeDAO.remove(notice);
		noticeDAO.flush();
	}

	/**
	 * Save an existing Notice entity
	 * 
	 */
	@Transactional
	public void saveNotice(Notice notice) {
		Notice existingNotice = noticeDAO.findNoticeByPrimaryKey(notice.getSchoolId(), notice.getTime());

		if (existingNotice != null) {
			if (existingNotice != notice) {
				existingNotice.setSchoolId(notice.getSchoolId());
				existingNotice.setTime(notice.getTime());
				existingNotice.setTitle(notice.getTitle());
				existingNotice.setSummary(notice.getSummary());
				existingNotice.setAuthor(notice.getAuthor());
				existingNotice.setContent(notice.getContent());
			}
			notice = noticeDAO.store(existingNotice);
		} else {
			notice = noticeDAO.store(notice);
		}
		noticeDAO.flush();
	}

	/**
	 * Return all Notice entity
	 * 
	 */
	@Transactional
	public List<Notice> findAllNotices(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Notice>(noticeDAO.findAllNotices(startResult, maxRows));
	}

	/**
	 * Return a count of all Notice entity
	 * 
	 */
	@Transactional
	public Integer countNotices() {
		return ((Long) noticeDAO.createQuerySingleResult("select count(*) from Notice o").getSingleResult()).intValue();
	}
}
